package com.randb.easyhttp.request;

import com.randb.easyhttp.callback.Callback;
import com.randb.easyhttp.func.RetryExceptionFunc;
import com.randb.easyhttp.subscriber.DownloadSubscriber;
import com.randb.easyhttp.transformer.HandleErrorTransformer;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * User: RandBII
 * Date: 2020/6/1
 * Description:
 */
@SuppressWarnings("unchecked")
public class DownloadRequest extends BaseRequest<DownloadRequest> {

    private String saveName;
    private String savePath;


    public DownloadRequest saveName(String name) {
        this.saveName = name;
        return this;
    }

    public DownloadRequest savePath(String path) {
        this.savePath = path;
        return this;
    }

    public DownloadRequest(String url) {
        super(url);
    }

    @Override
    protected Observable<ResponseBody> generateRequest() {
        return apiManager.downloadFile(url);
    }

    public <T> Disposable execute(Callback<T> callback) {
        return (Disposable) build().generateRequest()
                .compose(new ObservableTransformer<ResponseBody, ResponseBody>() {

                    @Override
                    public ObservableSource<ResponseBody> apply(Observable<ResponseBody> upstream) {
                        if (isSyncRequest) {
                            return upstream;
                        } else {
                            return upstream.subscribeOn(Schedulers.io())
                                    .unsubscribeOn(Schedulers.io())
                                    .observeOn(Schedulers.computation());
                        }
                    }
                }).compose(new HandleErrorTransformer())
                .retryWhen(new RetryExceptionFunc(retryCount, retryDelay, retryIncreaseDelay))
                .subscribeWith(new DownloadSubscriber(context, savePath, saveName, callback));

    }
}
